package com.chenyue.cm.pay.iap;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import javax.net.ssl.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

/**
 * 苹果IAP内购验证工具类
 *
 * @author libingxing
 * @date 2019/2/26
 */
public class IosVerifyUtil {
    private static class TrustAnyTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static final String URL_SANDBOX = "https://sandbox.itunes.apple.com/verifyReceipt";

    private static final String URL_VERIFY = "https://buy.itunes.apple.com/verifyReceipt";

    /**
     * 苹果服务器验证
     *
     * @param receipt 账单
     * @return null 或返回结果 沙盒 https://sandbox.itunes.apple.com/verifyReceipt
     * url 要验证的地址
     */
    public static String buyAppVerify(String receipt, int type) {
//        防止返回的base64+号变成空格
        receipt = receipt.replace(" ", "+");
        //环境判断 线上/开发环境用不同的请求链接
        String url;
        if (type == 0) {
            //沙盒测试
            url = URL_SANDBOX;
        } else {
            //线上测试
            url = URL_VERIFY;
        }

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            URL console = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "text/json");
            conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            BufferedOutputStream hurlBufOus = new BufferedOutputStream(conn.getOutputStream());

            //拼成固定的格式传给平台
            String str = "{\"receipt-data\":\"" + receipt + "\"}";
            hurlBufOus.write(str.getBytes());
            hurlBufOus.flush();

            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            return sb.toString();
        } catch (Exception ex) {
            System.out.println("苹果服务器异常");
            ex.printStackTrace();
        }
        return null;
    }

    enum requestState {
        /**
         * 成功
         */
        SUCCESS("0"),

        /**
         * 沙箱
         */
        SAND_BOX("21007");

        String code;

        requestState(String code) {
            this.code = code;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }
    }

    /**
     * 苹果服务器远程验证订单
     *
     * @param transactionId 事务id
     * @param payload       验证内容
     * @return 返回""表示正常  不为空则提示错误信息
     */
    public static String verifyAppleOrder(
            String verifyResult, String transactionId, String payload
    ) {
        payload = payload.replace(" ", "+");

//        verifyResult 入库记录
        if (verifyResult == null) {
            return "苹果服务器验证失败";
        } else {
            JSONObject appleReturn = JSONObject.parseObject(verifyResult);
            String states = appleReturn.getString("status");
            //无数据则沙箱环境验证
            if (requestState.SAND_BOX.code.equals(states)) {
                verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);
                appleReturn = JSONObject.parseObject(verifyResult);
                states = appleReturn.getString("status");
            }
            // 前端所提供的收据是有效的    验证成功
            if (requestState.SUCCESS.code.equals(states)) {
                String receipt = appleReturn.getString("receipt");
                JSONObject returnJson = JSONObject.parseObject(receipt);
                String inApp = returnJson.getString("in_app");
                List<JSONObject> inApps = JSONObject.parseArray(inApp, JSONObject.class);
                if (!CollectionUtils.isEmpty(inApps)) {
                    ArrayList<String> transactionIds = new ArrayList<>();
                    for (JSONObject app : inApps) {
                        transactionIds.add(app.getString("transaction_id"));
                    }
                    if (transactionIds.contains(transactionId)) {
                        //交易列表包含当前交易，则认为交易成功
                        return "";
                    } else {
                        return "当前交易不在交易列表中";
                    }
                }
                return "未能获取获取到交易列表";
            } else {
                return "支付失败，错误码：" + states;
            }
        }
    }

}
